<?php

namespace app\admin\controller;

use think\Db;

class User extends Base
{
    public function login()
    {
        $request = request();
        $where = [];
        input('mobile') ? $where['mobile'] = input('mobile') : $this->err('缺少手机号！');
        input('password') ? $where['password'] = md5(input('password')) : $this->err('缺少密码！');

        $field = 'password, payPwd,uid';
        $member = model('user')->where($where)->field($field, true)->find();
        if (empty($member)) {
            $this->err('手机或密码错误！');
        }
        if ($member['userStatus'] == 0) {
            $this->err('该用户未激活，请先激活！');
        }
        if ($member['userStatus'] == -1) {
            $this->err('该用户已被冻结，请联系管理员！');
        }
        if ($member['userType'] != 2) {
            $this->err('该用户不是管理员，无法登陆后台！');
        }
        $token = md5($member['id'] + time());
        S("u" . $member['id'], $token, 60 * 60 * 24);
        // session('token', $token);
        //更新用户表
        $data = [
            'lastLoginTime' => createTime(),
            'lastIP' => $request->ip()
        ];
        D('user')->editData($data, $member['id']);
        $rep = ['userInfo' => $member, 'token' => $token];
        $this->suc($rep);
    }

    public function addUser()
    {
        $data = [];
        $data['name'] = input('name');
        $data['password'] = input('password');
        $data['mobile'] = input('mobile');
        $data['IDCards'] = input('IDCards');
        $data['isGoodEmployer'] = input('isGoodEmployer');
        $data['avatar'] = input('avatar');
        $data['province'] = input('province');
        $data['city'] = input('city');
        $data['district'] = input('district');
        $data['street'] = input('street');

        $result = $this->validate($data, 'User');
        if ($result !== true) {
            $this->err($result);
        }
        $data['password'] = md5($data['password']);

        //删除空的字段
        foreach ($data as $key => $value) {
            if (empty($value)) {
                unset($data['$key']);
            }
        }

        $res = model('user')->editData($data);
        $res ? $this->suc($res) : $this->err('添加用户出错！');
    }

    public function editUser()
    {
        $data = [];
        $data['id'] = input('cid');
        $data['name'] = input('name');
        $data['mobile'] = input('mobile');
        $data['IDCards'] = input('IDCards');
        $data['isGoodEmployer'] = input('isGoodEmployer');
        $data['isGoodWorker'] = input('isGoodWorker');
        $data['isOpenFollow'] = input('isOpenFollow');
        $data['isOpenChat'] = input('isOpenChat');
        $data['isHiddenMobile'] = input('isHiddenMobile');
        $data['avatar'] = input('avatar');
        input('province') ? $data['province'] = input('province') : $this->err('缺少地址！');
        input('city') ? $data['city'] = input('city') : $this->err('缺少地址！');
        input('district') ? $data['district'] = input('district') : $this->err('缺少地址！');
        input('street') ? $data['street'] = input('street') : $this->err('缺少地址！');
        //     input('Introduction') ? $data['Introduction'] = input('Introduction') :true;
        $data['uid'] = input('uid') ? input('uid') : 1;
        if (empty($data['id'])) {
            $this->err('缺少用户主键！');
        }
        $result = $this->validate($data, 'User');
        if ($result !== true) {
            $this->err($result);
        }
        //删除空的字段
        foreach ($data as $key => $value) {
            if (empty($value) && $value != 0) {
                unset($data['$key']);
            }
        }

        input('reward') ? $data['reward'] = input('reward') : true;
        input('money') ? $data['money'] = input('money') : true;
        input('charm') ? $data['charm'] = input('charm') : true;
        input('points') ? $data['points'] = input('points') : true;

        $res = model('user')->editData($data, $data['id'], $data['uid']);
        if ($res == 0 || $res) {
            $this->suc($res);
        } else {
            $this->err('修改用户出错！');
        }
    }

    /**
     *  sign  1-增加 2-减少
     *  cid 用户编码
     *  type  1-赏金 2 余额 3 积分 4 魅力分
     */
    public function editNumber()
    {
        $data = [];
        $where = [];
        input('cid') ? $data['id'] = input('cid') : $this->err('缺少用户主键！');
        input('sign') ? $data['sign'] = input('sign') : $this->err('缺少类型！');
        input('score') ? $data['score'] = input('score') : $this->err('缺少修改数值！');
        input('type') ? $data['type'] = input('type') : $this->err('缺少选择类型！');
        $where['id'] = $data['id'];
        Db::startTrans();
        try {
            // 1 赏金 2 钱包金额 3 积分 4 魅力值
            switch ($data['type']) {
                case 1:
                    $res = model('user')->editScore($data['id'], $data['sign'], $data['score'], 3, 2);
                    break;
                case 2:
                    $res = model('user')->editScore($data['id'], $data['sign'], $data['score'], 4, 4);
                    break;
                case 3:
                    $res = model('user')->editScore($data['id'], $data['sign'], $data['score'], 2, 2);
                    break;
                case 4:
                    $res = model('user')->editScore($data['id'], $data['sign'], $data['score'], 1, 2);
                    break;
                default:
                    $res = [];
                    $this->err('选择类型错误！');
                    break;
            }
            // 提交事务
            Db::commit();
            $res['status'] ? $this->suc($res['content']) : $this->err($res['msg']);
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->err('操作失败！');
        }

    }

    public function disableUser()
    {
        $data = [];
        $data['id'] = input('cid');
        input('userStatus') != null ? $data['userStatus'] = input('userStatus') : $this->err('缺少审核状态！');
        $data['uid'] = input('uid') ? input('uid') : 1;

        if (empty($data['id'])) {
            $this->err('缺少用户主键！');
        }

        $res = model('user')->editData($data, $data['id'], $data['uid']);
        $res ? $this->suc($res) : $this->err('修改用户出错！');
    }

    /**
     * 获取用户列表
     */
    public function getUserList()
    {
        $where = [];

        input('userType') ? $where['userType'] = input('userType') : true;

        input('cid') ? $where['id'] = input('cid') : true;

        input('userStatus') ? $where['userType'] = input('userStatus') : true;

        input('name') ? $where['name'] = ['like',input('name') . '%'] : true;

        input('mobile') ? $where['mobile'] = ['like',input('mobile') . '%'] : true;

        input('charm') ? $where['charm'] = input('charm') : true ;

        input('city') ? $where['city'] = ['like',input('city') . '%'] : true ;

        input('createTime') ? $where['createTime'] = ['like',input('createTime') . '%'] : true ;

        $res = model('user')->getListByPage($where);

        $res ? $this->suc($res) : $this->err('获取用户列表出错！');
    }

    public function getUserDetail()
    {
        $where = [];
        if (!input('cid')) {
            $this->err('缺少用户主键！');
        }
        $where['id'] = input('cid');

        $res = model('user')->where($where)->find();
        $inviteCount = model('user_charm')->field('friendInvite')->where(['cid' => $where['id']])->find();
        $res['inviteCount'] = $inviteCount['friendInvite'];
        $res ? $this->suc($res) : $this->err('获取用户详情出错！');
    }

    public function editPwd()
    {

        $data = [];

        if (input('password') && input('payPwd')) {
            $this->err('一次只能修改一个密码！');
        } elseif (input('password')) {
            if (strlen(input('password')) < 6) {
                $this->err('密码长度必须大于6！');
            } else {
                $data['password'] = md5(input('password'));
            }
        } elseif (input('payPwd')) {
            if (strlen(input('payPwd')) < 6) {
                $this->err('密码长度必须大于6！');
            } else {
                $data['payPwd'] = md5(input('payPwd'));
            }
        } else {
            $this->err('密码不能为空！');
        }

        $data['id'] = input('cid');
        $data['uid'] = input('uid');

        if (empty($data['id'])) {
            $this->err('缺少用户主键！');
        }

        $res = model('user')->editData($data, $data['id'], $data['uid']);
        if ($res == 0 || $res) {
            $this->suc($res);
        } else {
            $this->err('修改用户密码出错！');
        }
    }

    public function editUserPoints()
    {
        $data = [];
        $u_data = [];
        input('score/d') > 0 ? $data['score'] = abs(input('score')) : $this->err('分值不正确！');
        input('type/d') > 0 ? $data['type'] = input('type/d') : $this->err('操作类型不正确！');
        input('sign/d') == 1 || input('sign/d') == 2 ? $data['sign'] = input('sign/d') : $this->err('sign有误！');
        input('cid') == null ? $this->err('缺少用户id！') : $data['cid'] = input('cid');
        $data['source'] = 2; // 后台操作
        $data['createTime'] = createTime();
        $u_data = [
            'id' => $data['cid'],
            'userStatus' => 1
        ];
        $user = model('user')->where($u_data)->field('id, reward, money, charm, points')->find();
        if (empty($user)) {
            $this->err('不存在该用户，或已被删除！');
        }

        Db::startTrans();
        try {
            switch ($data['type']) {
                case 1:
                    $data['sign'] == 1 ? $data['leftScore'] = $user['reward'] + $data['score'] : $data['leftScore'] = $user['reward'] - $data['score'];
                    $data['leftScore'] < 0 ? $this->err('赏金不能减到负数！') : true;
                    $l_res = model('userRewardLog')->editData($data);
                    if (empty($l_res)) {
                        $this->err('日志插入错误！');
                    }
                    $u_data = [
                        'id' => $data['cid'],
                        'reward' => $data['leftScore']
                    ];
                    break;
                case 2:
                    $data['sign'] == 1 ? $data['leftMoney'] = $user['money'] + $data['score'] : $data['leftMoney'] = $user['money'] - $data['score'];
                    $data['leftMoney'] < 0 ? $this->err('余额不能减到负数！') : true;

                    //拼接资金流水表数据
                    $data['targetId'] = $data['cid'];
                    $data['orderSrc'] = 4;  //后台操作
                    $data['moneyType'] = $data['sign']; //1-收入 2-支出
                    $data['money'] = $data['score'];
                    $data['moneySn'] = createOrderCode('ZJ');

                    $l_res = model('userMoneyLog')->editData($data);
                    if (empty($l_res)) {
                        $this->err('日志插入错误！');
                    }
                    $u_data = [
                        'id' => $data['cid'],
                        'money' => $data['leftMoney']
                    ];
                    break;
                case 3:
                    $data['sign'] == 1 ? $data['leftScore'] = $user['charm'] + $data['score'] : $data['leftScore'] = $user['charm'] - $data['score'];
                    $data['leftScore'] < 0 ? $this->err('魅力值不能减到负数！') : true;
                    $l_res = model('userCharmLog')->editData($data);
                    if (empty($l_res)) {
                        $this->err('日志插入错误！');
                    }
                    $u_data = [
                        'id' => $data['cid'],
                        'charm' => $data['leftScore']
                    ];
                    break;
                case 4:
                    $data['sign'] == 1 ? $data['leftScore'] = $user['points'] + $data['score'] : $data['leftScore'] = $user['points'] - $data['score'];
                    $data['leftScore'] < 0 ? $this->err('积分不能减到负数！') : true;
                    $l_res = model('userPointsLog')->editData($data);
                    if (empty($l_res)) {
                        $this->err('日志插入错误！');
                    }
                    $u_data = [
                        'id' => $data['cid'],
                        'points' => $data['leftScore']
                    ];
                    break;
                default:
                    $this->err('分值类型错误！');
                    break;
            }

            $res = model('user')->editData($u_data, $u_data['id']);
            // 提交事务
            Db::commit();
            $res ? $this->suc('操作成功！') : $this->err('操作失败！');
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            $this->err('操作失败！');
        }
    }

    /**
     *  relationType 1-雇佣 2-预约 3-关注
     *  cid 用户编码
     *  userType 1-雇主 2-阿姨
     */
    public function getUserRelationList()
    {
        /* $where = [];
         $data = [];
         $data['relationType'] = input('relationType');
         if (input('userType') == 1) {
             input('cid') ? $where['employeeId'] = input('cid') : $this->err('缺少用户主键');
         } elseif (input('userType') == 2) {
             input('cid') ? $where['workId'] = input('cid') : $this->err('缺少用户主键');
         } else {
             $this->err('用户类型错误！');
         }


         $field = 'u.id as workId, u.avatar,u.street ,u.name,u.job,u.age,u.city,DATE_FORMAT(u.beginTime,\'%H:%i\')as beginTime,DATE_FORMAT(u.endTime,\'%H:%i\')as endTime,u.workYear,u.workDuty,u.salary,u.rest,
         u.legalRest,u.introduction,u.pictureSrc1,u.pictureSrc2,u.pictureSrc3,u.videoSrc';

         switch ($data['relationType']) {
             case 1:
                 $where['isHire'] = 1;
                 $res = model('user_relation')
                     ->alias('uR')
                     ->field($field . ', uR.hireTime as finishTime')
                     ->join('user u', 'u.id=uR.workId', 'left')
                     ->where($where)
                     ->order('uR.id desc')
                     ->paginate(10)
                     ->toArray();
                 $res ? $this->suc($res) : $this->err('获取信息失败');
                 break;
             case 2:
                 $where['isOrder'] = 1;
                 $res = model('user_relation')
                     ->alias('uR')
                     ->field($field . ', uR.orderTime as finishTime')
                     ->join('user u', 'u.id=uR.workId', 'left')
                     ->where($where)
                     ->order('uR.id desc')
                     ->paginate(10)
                     ->toArray();
                 $res ? $this->suc($res) : $this->err('获取信息失败');
                 break;
             case 3:
                 $where['isFollow'] = 1;
                 $res = model('user_relation')
                     ->alias('uR')
                     ->field($field . ', uR.followTime as finishTime')
                     ->join('user u', 'u.id=uR.workId', 'left')
                     ->where($where)
                     ->order('uR.id', 'desc')
                     ->paginate('10')
                     ->toArray();
                 $res ? $this->suc($res) : $this->err('获取信息失败');
                 break;

             default:
                 $this->err('用户关系错误！');
                 break;

         }*/
        $where = [];
        input('relationType') ? $relationType = input('relationType') : $this->err('缺少选择类型 ！');
        input('userType') ? $userType = input('userType') : $this->err('缺少用户类型 ！');
        input('cid') ? $cid = input('cid') : $this->err('缺少用户主键 ！');
        if ($userType == 1) {
            $where['employeeId'] = $cid;
        } elseif ($userType == 2) {
            $where['workId'] = $cid;
        } else {
            $this->err('用户类型错误！');
        }

        $field = 'uR.employeeId as employeeId,uR.workId as workId, u.avatar,u.street ,u.name,u.job,u.age,u.city,
        DATE_FORMAT(u.beginTime,\'%H:%i\')as beginTime,DATE_FORMAT(u.endTime,\'%H:%i\')as endTime,u.workYear,u.workDuty,u.salary,u.rest,
        u.legalRest,u.introduction,u.pictureSrc1,u.pictureSrc2,u.pictureSrc3,u.videoSrc,u.userType';

        switch ($relationType) {
            case 1:
                if ($userType == 1) {
                    $where['isHire'] = 1;
                    $res = model('user_relation')
                        ->alias('uR')
                        ->field($field . ', uR.hireTime as finishTime,uR.managedWages,uR.settlementTime,uR.trusteeshipStatus')
                        ->join('user u', 'u.id=uR.workId', 'left')
                        ->where($where)
                        ->order('uR.id desc')
                        ->paginate(10)
                        ->toArray();

                } else {
                    $where['isHire'] = 1;
                    $res = model('user_relation')
                        ->alias('uR')
                        ->field($field . ', uR.hireTime as finishTime')
                        ->join('user u', 'u.id=uR.employeeId', 'left')
                        ->where($where)
                        ->order('uR.id desc')
                        ->paginate(10)
                        ->toArray();
                }
                $res ? $this->suc($res) : $this->err('获取信息失败');
                break;
            case 2:
                if ($userType == 1) {
                    $where['isOrder'] = 1;
                    $res = model('user_relation')
                        ->alias('uR')
                        ->field($field . ', uR.orderTime as finishTime')
                        ->join('user u', 'u.id=uR.workId', 'left')
                        ->where($where)
                        ->order('uR.id desc')
                        ->paginate(10)
                        ->toArray();
                } else {
                    $where['isOrder'] = 1;
                    $res = model('user_relation')
                        ->alias('uR')
                        ->field($field . ', uR.orderTime as finishTime')
                        ->join('user u', 'u.id=uR.employeeId', 'left')
                        ->where($where)
                        ->order('uR.id desc')
                        ->paginate(10)
                        ->toArray();
                }

                $res ? $this->suc($res) : $this->err('获取信息失败');
                break;
            case 3:
                $e_where['isFollow'] = 3;
                if (input('userType') == 1) {
                    $where['isFollow'] = 1;
                    $res = model('user_relation')
                        ->alias('uR')
                        ->field($field . ', uR.followTime as finishTime')
                        ->join('user u', 'u.id=uR.workId', 'left')
                        ->where($where)
                        ->whereor($e_where)
                        ->order('uR.id', 'desc')
                        ->paginate('10')
                        ->toArray();

                    $res ? $this->suc($res) : $this->err('获取信息失败！');
                } else {
                    $where['isFollow'] = 2;
                    $res = model('user_relation')
                        ->alias('uR')
                        ->field($field . ', uR.followTime as finishTime')
                        ->join('user u', 'u.id=uR.employeeId', 'left')
                        ->where($where)
                        ->whereor($e_where)
                        ->order('uR.id', 'desc')
                        ->paginate('10')
                        ->toArray();

                    $res ? $this->suc($res) : $this->err('获取信息失败');
                }
                break;

            default:
                $this->err('用户关系错误！');
                break;

        }

    }

    public function addRelation()
    {
        $data = [];
        $data['cid'] = input('cid');
        input('workId') ? $data['workId'] = input('workId') : $this->err('缺少家政编码');
        $data['isOrder'] = 1;
        $res = model('')->editData($data);
        $res ? $this->suc($res) : $this->err('预约失败');
    }

    public function getUserOrderList()
    {
        $where = [];
        $data = [];
        input('orderSn') ? $where['orderSn'] = ['like', '%' . input('orderSn') . '%'] : true;
        input('paymentStatus') ? $data['paymentStatus'] = input('paymentStatus') : true;
        input('cancelStatus') ? $data['cancelStatus'] = input('cancelStatus') : true;
        input('cid') ? $where['employeeId'] = input('cid') : $this->err('缺少用户主键');

        $res = model('order')->getListByPage($where, 10, '', 'paymentStatus desc,cancelStatus desc');
        $res ? $this->suc($res) : $this->err('获取订单列表失败');

    }

    public function getUserCollectList()
    {
        $where = [];
        input('cid') ? $where['cid'] = input('cid') : $this->err('缺少用户主键');
        $where['isCollect'] = 1;
        $res = model('user_article')
            ->alias('ua')
            ->field('a.content,a.title,a.commentCount,a.collectCount,a.sort')
            ->join('article a', 'ua.articleId=a.id', 'left')
            ->where($where)
            ->paginate(10)
            ->toArray();
        $res ? $this->suc($res) : $this->err('获取点赞列表失败');
    }

    public function getUserFriendList()
    {
        $where = [];
        $data = [];
        $field = 'name,mobile,userType,charm,street';
        input('id') ? $data['id'] = input('id') : $this->err('缺少用户主键');
        $where['leaderId'] = $data['id'];

        $res = model('user')->getToListByPage($where, 10, $field);
        $res ? $this->suc($res) : $this->err('获取我的推荐好友失败');

    }


    /**
     *  获取用户优惠券列表
     */
    public function getUserCouponList()
    {
        $where = [];
        input('cid') ? $where['cid'] = input('cid') : $this->err('缺少用户主键！');
        //1 -未使用的优惠券
        $where['uc.status'] = 1;

        $res = model('user_coupon')
            ->alias('uc')
            ->field('c.* ,uc.overTime')
            ->join('coupon c', 'uc.couponId=c.id', 'left')
            ->where($where)
            ->order('uc.id desc')
            ->paginate()
            ->toArray();

        $res ? $this->suc($res) : $this->err('获取用户优惠券列表失败');
    }


    /**
     * 获取用户钱包日志
     */
    public function getUserMoneyList()
    {
        $where = [];
        input('cid') ? $where['targetId'] = input('cid') : $this->err('缺少用户主键！');
        $res = model('user_money_log')
            ->alias('l')
            ->field('l.*,o.type')
            ->join('order o', 'o.id=l.orderId', 'left')
            ->where($where)
            ->order('l.id desc')
            ->paginate(10)
            ->toArray();

        $res ? $this->suc($res) : $this->err('获取资金列表失败！');
    }

    /**
     * 获取用户资金详情
     */
    public function getUserMoneyDetail()
    {
        $where = [];
        input('cid') ? $where['targetId'] = input('cid') : $this->err('缺少用户主键');
        input('id') ? $where['um.id'] = input('id') : $this->err('缺少钱包日志主键');
        $res = model('user_money_log')
            ->alias('um')
            ->field('um.moneySn,u.mobile,u.name,um.moneyType,um.money,um.orderSrc,um.leftMoney')
            ->join('user u', 'u.id=um.targetId', 'left')
            ->where($where)
            ->find();

        $res ? $this->suc($res) : $this->err('获取用户详资金情失败');
    }

    /**
     * 获取用户赏金日志
     */
    public function getUserRewardList()
    {
        $where = [];
        input('cid') ? $where['cid'] = input('cid') : $this->err('缺少用户主键');

        $res = model('user_reward_log')->getListByPage($where, 10);
        $res ? $this->suc($res) : $this->err('获取用户赏金日志失败！');

    }

    /**
     * 获取用户积分日志
     */
    public function getUserPointList()
    {
        $where = [];
        input('cid') ? $where['cid'] = input('cid') : $this->err('缺少用户主键');

        $res = model('user_Points_log')->getListByPage($where, 10);
        $res ? $this->suc($res) : $this->err('获取用户积分日志失败！');
    }

    /**
     * 获取用户魅力分日志
     */
    public function getUserCharmList()
    {
        $where = [];
        input('cid') ? $where['cid'] = input('cid') : $this->err('缺少用户主键');

        $res = model('user_charm_log')->getListByPage($where, 10);
        $res ? $this->suc($res) : $this->err('获取用户魅力分日志失败！');
    }

    /**
     * 修改用户状态
     */
    public function changeUserType()
    {
        $data = [];
        $where = [];
        input('cid') ? $where['id'] = input('cid') : $this->err('缺少用户主键');
        //当前查询用户状态
        $user = model('user')->field('userType')->where($where)->find();
        if (!$user) {
            $this->err('用户主键错误！');
        }
        if ($user['userType'] == 1) {
            $data['id'] = $where['id'];
            $data['userType'] = 2;
            $res = model('user')->editData($data, $data['id']);
        } else {
            $data['id'] = $where['id'];
            $data['userType'] = 1;
            $res = model('user')->editData($data, $data['id']);
        }
        $res ? $this->suc($res) : $this->err('修改失败！');
    }

    /**
     * 提现列表
     * status 1 完成 2 待处理 3 已取消
     */
    public function pushMoneyTakeList()
    {
        $where = [];
//        $where['uc.status'] = 2;
        input('bank') ? $where['uc.bank'] = input('bank') : true;
        input('bankNumber') ? $where['uc.bankNumber'] = input('bankNumber') : true;
        $res = model('user_cash')
            ->alias('uc')
            ->field('uc.*,u.mobile as userMobile,u.name as userName, abs(uc.status - 2) as orderSn')
            ->join('user u', 'uc.cid=u.id', 'left')
            ->where($where)
            ->order('orderSn ,uc.createTime desc')
            ->paginate(10)
            ->toArray();
        $res ? $this->suc($res) : $this->err('没有查询到相关数据！');

    }

    /**
     * 审计提现
     * status 1 完成 2 待处理 3 已取消
     * type 1-钱包提现 2-赏金提现
     */
    public function auditCashStatus()
    {
        $data = [];
        input('cashId') ? $data['id'] = input('cashId') : $this->err('缺少提现编码！');
        input('status') ? $data['status'] = input('status') : $this->err('缺少处理状态！');
        // 启动事务
        Db::startTrans();
        try {
            $res = model('user_cash')->editData($data, $data['id']);

            // 如果申请不通过，则返还余额或钱包
            if ($data['status'] == 3) {
                $cash = model('user_cash')->where(['id' => $data['id']])->find();
                $user = model('user')->where(['id' => $cash['cid']])->find();

                //type 1-钱包提现，返还钱包 2-赏金提现 ，返还赏金
                if ($cash['type'] == 1) {
                    $user_data = [
                        'id' => $cash['cid'],
                        'money' => $user['money'] + $cash['money']
                    ];
                    $userLong_data = [
                        'targetId' => $cash['cid'],
                        'moneyType' => 1,
                        'money' => $cash['money'],
                        'leftMoney' => $user['money'] + $cash['money'],
                        'orderSrc' => 6,
                        'createTime' => createTime()
                    ];
                    model('user_money_log')->editData($userLong_data);
                } else {
                    $user_data = [
                        'id' => $cash['cid'],
                        'reward' => $user['reward'] + $cash['money']
                    ];
                    $l_data = [
                        'leftScore' => $user['reward'] + $cash['money'],
                        'score' => $cash['money'],
                        'createTime' => createTime(),
                        'sign' => 1,
                        'cid' => $cash['cid'],
                        'followId' => 0,
                        'source' => 7
                    ];
                    $l_res = model('user_reward_log')->editData($l_data);
                }
                model('user')->editData($user_data, $user_data['id']);
            }
            // 提交事务
            if ($res) {
                Db::commit();
                $this->suc('操作成功！');
            } else {
                Db::rollback();
                $this->err('处理失败！');
            }
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            //   $this->err($e);
            $this->err('操作失败！');
        }
    }

    /**
     * 操作托管金额
     */
    public function auditTrusteeshipStatus()
    {
        input('employeeId') ? $data['employeeId'] = input('employeeId') : $this->err('缺少主键！');
        input('workId') ? $data['workId'] = input('workId') : $this->err('缺少主键！');
        input('money') ? $data['managedWages'] = input('money') : $this->err('缺少金额！');
//       $data['trusteeshipStatus']=1;
        $relation = model('user_relation')->where(['employeeId' => $data['employeeId'], 'workId' => $data['workId']])->find();
        $data['id'] = $relation['id'];
        $res = model('user_relation')->editData($data, $data['id']);
        $res ? $this->suc($data) : $this->err('操作失败！');
    }

    /**
     * 刷脸登记申请列表
     */
    public function getFacedList()
    {
        $where = [];

        $where['isFaced'] = 2;
        $res = model('user')->getListByPage($where);
        $res ? $this->suc($res) : $this->err('获取列表失败！');
    }

    /**
     *
     * 审计刷脸登记
     */
    public function auditFaced()
    {
        $data = [];
        input('cid') ? $data['id'] = input('cid') : $this->err('缺少用户主键！');
        input('isFaced') ? $data['isFaced'] = input('isFaced') : $this->err('缺少审计状态！');
        $data['isRealed'] = input('isFaced');

        $user = model('user')->where(['id' => input('cid')])->find();
        //查询系统配置刷脸登记奖励多少魅力值
        $sy = model('system_config')->where(['status' => 1])->find();
        $sy ? true : $this->err('查询系统配置失败！');
        $data['charm'] = $user['charm'] + $sy['faceValue'] + $sy['realValue'];
        $uc_data = [
            'cid' => $data['id'],
            'safeExamPercent' => $sy['faceValue'],
            'realPoints' => $sy['realValue']
        ];
        //魅力值日志
        $log_data = [
            $log1_data = [
                'sign' => 1,
                'cid' => $data['id'],
                'source' => 3,
                'score' => $sy['faceValue'],
                'leftScore' => $user['charm'] + $sy['faceValue']
            ],
            $log2_data = [
                'sign' => 1,
                'cid' => $data['id'],
                'source' => 4,
                'score' => $sy['realValue'],
                'leftScore' => $user['charm'] + $sy['faceValue'] + $sy['realValue']
            ]
        ];

        //启动事务
        Db::startTrans();
        try {
            if ($data['isFaced'] == 3) {
                $res = model('user')->editData($data, $data['id']);
            } else {
                $res = model('user')->editData($data, $data['id']);
                //更新魅力值表
                $user_charm = model('user_charm')->where(['cid' => input('cid')])->find();

                if (empty($user_charm)) {
                    $uc_data['createTime'] = createTime();
                    $uc_res = model('user_charm')->editData($uc_data);
                } else {
                    $uc_res = model('user_charm')->where(['cid' => $uc_data['cid']])->update($uc_data);
                }
                $uc_res ? true : $this->err('更新用户魅力表失败！');
                //批量新增
                model('user_charm_log')->saveAll($log_data);
            }
            if ($res) {
                Db::commit();
                $this->suc('审核成功！');
            } else {
                Db::rollback();
                $this->err('审核失败！');
            }

        } catch (\Exception $e) {
            //回滚事务
            Db::rollback();
            $this->err('操作失败！');
        }
    }

    /**
     *
     * 删除用户视频
     */
    public function delUserVideoSrc()
    {
        $data = [];
        input('cid') ? $data['id'] = input('cid') : $this->err('缺少用户主键！');

        $data['videoSrc'] = '';
        $data['videoPicSrc'] = '';

        $res = model('user')->editData($data, $data['id']);
        $res ? $this->suc($res) : $this->err('删除失败！');

    }

    /**
     *
     * 删除用户照片
     */
    public function editUserResource()
    {
        $data = [];
        input('cid') ? $data['id'] = input('cid') : $this->err('缺少用户主键！');

        if (is_string(input('pictureSrc1'))) {
            $data['pictureSrc1'] = input('pictureSrc1');
        }
        if (is_string(input('pictureSrc2'))) {
            $data['pictureSrc2'] = input('pictureSrc2');
        }
        if (is_string(input('pictureSrc3'))) {
            $data['pictureSrc3'] = input('pictureSrc3');
        }

        $res = model('user')->editData($data, $data['id']);
        $res ? $this->suc($res) : $this->err('删除失败！');

    }
    /**
     * 删除用户
     */
    public function delUser(){

        $where=[];

        input('cid') ? $cid =input('cid'): $this->err('缺少用户主键！');

        $userType = model('user')->field('userType')->where(['id'=>$cid])->find();

        $result = Db::query("call delUser('$cid','$userType')");
        $this->suc(1);
    }
    /**
     * 修改上级用户编码
     */

    public function editUserLeaderId(){

        $data = [];
        $where =[];
        input('cid') ? $where['cid'] = input('cid') : $this->err('去缺少用户主键！');
        input('leaderId') ? $data['leaderId'] = input('leaderId') : $this->err('缺少上级用户主键！');

        $user = model('user')->field('leaderId,charm,inviteCount')->where(['id'=>$where['cid']])->find();

        if($user['leaderId']==0){//没有上级用户时
            Db::startTrans();
            try {
              //修改上级用户编码
              $rep = model('user')->where(['id'=>$where['cid']])->update(['leaderId'=>$data['leaderId']]);

              //查询上级用户用户表信息
              $leaderId = model('user')->field('leaderId,charm,inviteCount')->where(['id'=>$data['leaderId']])->find();

              //查询上级用户用户魅力表信息

               $charm = model('user_charm')->where(['cid'=>$data['leaderId']])->find();

              //查询邀请一个朋友新增的魅力分
                $sy = model('system_config')->where(['status'=>1])->find();
              //修改用户表上级用户信息
                $rep_data = [
                    'charm' => $leaderId['charm'] + $sy['friendInviteValue'],
                    'inviteCount' => $leaderId['inviteCount'] +1,
                ];
              $res = model('user')->where(['id'=>$data['leaderId']])->update($rep_data);

              //修改上级用户魅力表

                $leaderId_charm_data = [
                    'friendInvite'=>$charm['friendInvite']+1,
                ];

                $leaderId_charm = model('user_charm')->where(['cid'=>$data['leaderId']])->update($leaderId_charm_data);

                //新增上级用户魅力分日志表信息

                $log_data = [
                    'sign' =>1,
                    'cid'=>$data['leaderId'],
                    'inviteCid'=>$where['cid'],
                    'source'=>2,
                    'score'=>$sy['friendInviteValue'],
                    'leftScore'=>$leaderId['charm'] + $sy['friendInviteValue']
                ];

                $log = model('user_charm_log')->editData($log_data);

                if($res){
                    Db::commit();
                    $this->suc($res);
                } else {
                    Db::rollback();
                    $this->err('修改失败！');
                }
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->err('操作失败！');
            }
        }else{

            Db::startTrans();
            try {
                //修改上级用户编码
                $rep = model('user')->where(['id'=>$where['cid']])->update(['leaderId'=>$data['leaderId']]);

                //查询上级用户用户表信息
                $leaderId = model('user')->field('leaderId,charm,inviteCount')->where(['id'=>$data['leaderId']])->find();

                //查询原上级用户信息

                $YL_leaderId = model('user')->field('leaderId,charm,inviteCount')->where(['id'=>$user['leaderId']])->find();

                //查询上级用户用户魅力表信息

                $charm = model('user_charm')->where(['cid'=>$data['leaderId']])->find();

                //查询原上级用户用户魅力表信息

                $YL_charm = model('user_charm')->where(['cid'=>$user['leaderId']])->find();

                //查询邀请一个朋友新增的魅力分
                $sy = model('system_config')->where(['status'=>1])->find();
                //修改用户表上级用户信息
                $rep_data = [
                    'charm' => $leaderId['charm'] + $sy['friendInviteValue'],
                    'inviteCount' => $leaderId['inviteCount'] +1,
                ];
                $res = model('user')->where(['id'=>$data['leaderId']])->update($rep_data);

                //修改原用户表上级用户信息
                $YL_rep_data = [
                    'charm' => $YL_leaderId['charm'] - $sy['friendInviteValue'],
                    'inviteCount' => $YL_leaderId['inviteCount'] - 1,
                ];

                $YL_res = model('user')->where(['id'=>$user['leaderId']])->update($YL_rep_data);

                //修改上级用户魅力表

                $leaderId_charm_data = [
                    'friendInvite'=>$charm['friendInvite']+1,
                ];

                $leaderId_charm = model('user_charm')->where(['cid'=>$data['leaderId']])->update($leaderId_charm_data);

                //修改原上级用户魅力表

                $YL_leaderId_charm_data = [
                    'friendInvite'=>$charm['friendInvite'] - 1,
                ];

                $YL_leaderId_charm = model('user_charm')->where(['cid'=>$user['leaderId']])->update($leaderId_charm_data);

                //新增上级用户魅力分日志表信息

                $log_data = [
                    'sign' =>1,
                    'cid'=>$data['leaderId'],
                    'inviteCid'=>$where['cid'],
                    'source'=>2,
                    'score'=>$sy['friendInviteValue'],
                    'leftScore'=>$leaderId['charm'] + $sy['friendInviteValue']
                ];

                $log = model('user_charm_log')->insert($log_data);

                //新增原上级用户魅力分日志表信息

                $YL_log_data = [
                    'sign' =>2,
                    'cid'=>$user['leaderId'],
                    'source'=>2,
                    'score'=>$sy['friendInviteValue'],
                    'leftScore'=>$leaderId['charm'] - $sy['friendInviteValue'],
                ];

                $YL_log = model('user_charm_log')->insert($YL_log_data);
                if($res){
                    Db::commit();
                    $this->suc($res);
                } else {
                    Db::rollback();
                    $this->err('修改失败！');
                }
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
                $this->err('操作失败！');
            }

        }

    }
    /*public function  a(){
            $where=[];
            $cid=0;
            $b=strtotime('2018-08-18 17:06:54');
            $where['createTime']=['>= time',$b];
            $where['source']=8;
            $res=model('user_charm_log')->field('cid,count(cid)')->where($where)->group('cid')->select();
           foreach ($res as $value){

               $user=model('user')->where(['id'=>$value['cid']])->find();
               $up=model('user')->where(['id'=>$value['cid']])->update(['inviteCount'=>$value['count(cid)']]);
               dump($value['cid']);
           }

        }*/
}